"use client"

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import { Button } from '@/components/ui/button';

export default function DashboardPage() {
  const router = useRouter();
  const { user, logout } = useAuth();

  useEffect(() => {
    if (!user) {
      router.push('/login');
    }
  }, [user, router]);

  const handleLogout = async () => {
    try {
      await fetch('/login/logout', {
        method: 'GET',
      });
      await logout();
      router.push('/login');
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  if (!user) {
    return null;
  }

  return (
    <div className="min-h-screen bg-white p-8">
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-2xl font-bold">欢迎回来，{user.nickName || user.account}</h1>
          <Button
            onClick={handleLogout}
            className="bg-black text-white hover:bg-gray-800"
          >
            退出登录
          </Button>
        </div>
        <div className="bg-gray-50 p-6 rounded-lg shadow-sm">
          <h2 className="text-lg font-semibold mb-4">账户信息</h2>
          <div className="space-y-2">
            <p><span className="font-medium">账号：</span>{user.account}</p>
            <p><span className="font-medium">用户类型：</span>{user.accountType === 1 ? '管理员' : '普通用户'}</p>
            <p><span className="font-medium">邮箱：</span>{user.email || '未设置'}</p>
            <p><span className="font-medium">手机：</span>{user.phone || '未设置'}</p>
            <p><span className="font-medium">上次登录时间：</span>{user.lastLoginTime || '首次登录'}</p>
          </div>
        </div>
      </div>
    </div>
  );
}